package com.studor.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.studor.common.Result;
import com.studor.entity.Order;
import com.studor.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/order")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    @GetMapping("/list")
    @SaCheckLogin
    public Result<List<Order>> list() {
        List<Order> orders = orderService.list();
        return Result.success(orders);
    }
    
    @GetMapping("/my")
    @SaCheckLogin
    public Result<List<Order>> getMyOrders() {
        Integer accountId = StpUtil.getLoginIdAsInt();
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("id", accountId);
        List<Order> orders = orderService.list(wrapper);
        return Result.success(orders);
    }
    
    @GetMapping("/page")
    @SaCheckLogin
    public Result<IPage<Order>> page(@RequestParam(defaultValue = "1") Integer current,
                                     @RequestParam(defaultValue = "10") Integer size) {
        Page<Order> page = new Page<>(current, size);
        IPage<Order> result = orderService.page(page);
        return Result.success(result);
    }
    
    @PostMapping("/create")
    @SaCheckLogin
    public Result<Void> createOrder(@RequestBody Order order) {
        Integer accountId = StpUtil.getLoginIdAsInt();
        order.setOrderNum(UUID.randomUUID().toString());
        order.setId(accountId);
        order.setOrderTime(LocalDateTime.now());
        order.setType("未支付");
        order.setTotalAmount(233); // 默认宿舍费用
        orderService.save(order);
        return Result.success("创建订单成功");
    }
    
    @PutMapping("/pay/{orderNum}")
    @SaCheckLogin
    public Result<Void> payOrder(@PathVariable String orderNum) {
        Order order = orderService.getById(orderNum);
        if (order != null) {
            order.setType("已支付");
            orderService.updateById(order);
            return Result.success("支付成功");
        }
        return Result.error("订单不存在");
    }
} 